import { nextTick } from 'vue'
import router from '@/router';
import { Toastloading } from '@/utils/public';
import { token, userStore } from '@/pinia/modules/user' // TOKEN变量名
import { control } from '@/pinia/modules/control';
let loading:any;
router.beforeEach( async (to,from) => {
  loading = Toastloading();
  const ToKen = window.localStorage[token] || '';
  if(!ToKen) {
    control().removeEditableTabs()
    if(to.fullPath == '/login') return true
    return {
      path: '/login',
    }
  }else {
    if(to.fullPath == '/login') return {
      path:from.path
    }
    const { roles } = userStore();
    if(roles.length == 0) {
      await userStore().GetInfo()
      return {
        path:to.fullPath,
        query:to.query,
        replace: true
      } 
    }
    handlemenu(to)
    return true
  }
})
router.afterEach( to => {
    loading.close();
    if (router.currentRoute.value.name === to.name) {
      nextTick(() => {
        const title:any = to.meta.title || ''
        document.title = title
      })
    }
})
/**
 * 追加历史菜单
 * @param to 路由参数
 * @returns 
 */
const handlemenu = (to:any = {})=>{
  const { path='' , meta={title:''} } = to
  const { title='' } = meta
  const useControl = control()
  useControl.editableTabsValue = to.path
  const tabList = useControl.editableTabs
  const index = tabList.findIndex(res=>res.name == path)
  if(index>= 0) return
  tabList.push({
    title:title,
    name:path,
  })
  useControl.editEditableTabs(tabList)
}